<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reservationApi, roomApi, timeUtils } from '../api/index'
import { useRouter } from 'vue-router'

const router = useRouter()
const rooms = ref([])
const loading = ref(false)
const currentUser = ref(JSON.parse(localStorage.getItem('user')) || null)
const selectedRoom = ref(null)
const conflictingReservations = ref([])

const reservationForm = ref({
  roomId: '',
  startTime: '',
  endTime: '',
  purpose: '',
  attendees: 1
})

const reservationFormRules = {
  roomId: [
    { required: true, message: '请选择会议室', trigger: 'change' }
  ],
  startTime: [
    { required: true, message: '请选择开始时间', trigger: 'change' }
  ],
  endTime: [
    { required: true, message: '请选择结束时间', trigger: 'change' }
  ],
  purpose: [
    { required: true, message: '请输入用途', trigger: 'blur' }
  ],
  attendees: [
    { required: true, message: '请输入参会人数', trigger: 'blur' },
    { type: 'number', min: 1, message: '参会人数必须大于0', trigger: 'blur' }
  ]
}

const reservationFormRef = ref(null)

onMounted(async () => {
  if (!currentUser.value) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }
  
  await fetchRooms()
})

const fetchRooms = async () => {
  loading.value = true
  try {
    const res = await roomApi.getAvailableRooms()
    rooms.value = res.data
  } catch (error) {
    console.error('获取可用会议室列表失败:', error)
    ElMessage.error('获取可用会议室列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

const handleRoomChange = () => {
  if (reservationForm.value.roomId && reservationForm.value.startTime && reservationForm.value.endTime) {
    checkTimeConflict()
  }
  
  // 更新选中的会议室信息
  selectedRoom.value = rooms.value.find(room => room.id === reservationForm.value.roomId)
}

const handleTimeChange = () => {
  if (reservationForm.value.roomId && reservationForm.value.startTime && reservationForm.value.endTime) {
    checkTimeConflict()
  }
}

const checkTimeConflict = async () => {
  if (!reservationForm.value.roomId || !reservationForm.value.startTime || !reservationForm.value.endTime) {
    return;
  }
  
  loading.value = true;
  try {
    const startTime = timeUtils.toISOString(reservationForm.value.startTime)
    const endTime = timeUtils.toISOString(reservationForm.value.endTime)
    const selectedRoomObj = rooms.value.find(room => room.id === reservationForm.value.roomId) || {}
    const roomName = selectedRoomObj.name
    
    console.log('检查时间冲突 - 开始时间:', startTime)
    console.log('检查时间冲突 - 结束时间:', endTime)
    console.log('检查时间冲突 - 本地开始时间:', timeUtils.formatLocal(reservationForm.value.startTime))
    console.log('检查时间冲突 - 本地结束时间:', timeUtils.formatLocal(reservationForm.value.endTime))
    console.log('检查时间冲突 - 会议室ID:', reservationForm.value.roomId)
    console.log('检查时间冲突 - 会议室名称:', roomName)
    
    // 使用API检查时间冲突
    const res = await reservationApi.checkTimeConflict(
      reservationForm.value.roomId,
      startTime,
      endTime,
      roomName
    )
    
    console.log('检查时间冲突 - 响应:', res.data)
    
    // 检查响应数据，更新冲突状态
    if (res.data && typeof res.data === 'object') {
      if (res.data.hasConflict) {
        ElMessage.warning('该时间段已被预约或有待审批的预约，请选择其他时间')
        conflictingReservations.value = Array.isArray(res.data.conflictingReservations) 
          ? res.data.conflictingReservations 
          : []
          
        // 显示冲突详情
        if (conflictingReservations.value.length > 0) {
          console.log('冲突预约详情:', conflictingReservations.value)
        }
      } else {
        conflictingReservations.value = []
      }
    } else {
      console.error('响应数据格式不正确:', res.data)
      ElMessage.error('检查时间冲突失败，响应数据格式不正确')
      conflictingReservations.value = []
    }
  } catch (error) {
    console.error('检查时间冲突失败:', error)
    console.error('错误详情:', error.response ? error.response.data : error.message)
    ElMessage.error('检查时间冲突失败，请稍后重试')
    conflictingReservations.value = []
  } finally {
    loading.value = false
  }
}

const submitForm = async () => {
  if (!reservationFormRef.value) return
  
  // 如果检测到冲突，显示提示并阻止提交
  if (hasTimeConflict.value) {
    console.error('提交阻止: 检测到时间冲突', conflictingReservations.value)
    ElMessage.error('存在时间冲突，请修改预约时间')
    ElMessageBox.alert('该时间段已被预约，无法提交申请', '预约冲突', {
      confirmButtonText: '我知道了',
      type: 'error'
    })
    return
  }
  
  await reservationFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        
        // 获取选中会议室对象
        const selectedRoomObj = rooms.value.find(room => room.id === reservationForm.value.roomId) || {}
        const roomName = selectedRoomObj.name
        
        // 强制再次检查时间冲突
        const startTime = timeUtils.toISOString(reservationForm.value.startTime)
        const endTime = timeUtils.toISOString(reservationForm.value.endTime)
        
        console.log('最终提交前检查时间冲突:', {
          roomId: reservationForm.value.roomId,
          roomName: roomName,
          startTime,
          endTime,
          localStartTime: timeUtils.formatLocal(reservationForm.value.startTime),
          localEndTime: timeUtils.formatLocal(reservationForm.value.endTime)
        })
        
        const conflictCheck = await reservationApi.checkTimeConflict(
          reservationForm.value.roomId,
          startTime,
          endTime,
          roomName
        )
        
        console.log('时间冲突检查结果:', conflictCheck.data)
        
        // 再次检查时间冲突
        if (conflictCheck.data && conflictCheck.data.hasConflict) {
          console.error('提交阻止: 最终检查发现时间冲突', conflictCheck.data.conflictingReservations)
          ElMessage.error('该时间段已被预约或有待审批的预约，无法提交')
          ElMessageBox.alert('该时间段已被预约，无法提交申请', '预约冲突', {
            confirmButtonText: '我知道了',
            type: 'error'
          })
          conflictingReservations.value = Array.isArray(conflictCheck.data.conflictingReservations) 
            ? conflictCheck.data.conflictingReservations 
            : []
          loading.value = false
          return
        }
        
        // 提交预约
        const reservationData = {
          roomId: reservationForm.value.roomId,
          userId: currentUser.value.id,
          startTime: startTime,
          endTime: endTime,
          purpose: reservationForm.value.purpose,
          attendees: reservationForm.value.attendees,
          status: 'PENDING'
        }
        
        console.log('提交预约数据:', reservationData)
        
        try {
          const createRes = await reservationApi.createReservation(reservationData)
          console.log('预约创建响应:', createRes.data)
          ElMessage.success('预约申请已提交，等待管理员审批')
          router.push('/my-reservations')
        } catch (createError) {
          console.error('创建预约失败:', createError)
          if (createError.response) {
            console.error('错误响应:', createError.response.data)
            if (createError.response.status === 409) {  // 409 Conflict
              ElMessage.error(createError.response.data?.message || '该时间段已被预约或有待审批的预约，请选择其他时间')
              ElMessageBox.alert('该时间段已被预约，请更换时间', '预约冲突', {
                confirmButtonText: '我知道了',
                type: 'error'
              })
              if (createError.response.data?.conflictingReservations) {
                conflictingReservations.value = createError.response.data.conflictingReservations
              }
            } else {
              ElMessage.error(createError.response.data?.message || '提交预约失败，请稍后重试')
            }
          } else {
            ElMessage.error('提交预约失败，请稍后重试')
          }
        } finally {
          loading.value = false
        }
      } catch (error) {
        console.error('提交预约失败:', error)
        if (error.response && error.response.data) {
          console.error('错误响应:', error.response.data)
          ElMessage.error(error.response.data.message || '提交预约失败，请稍后重试')
        } else {
          ElMessage.error('提交预约失败，请稍后重试')
        }
        loading.value = false
      }
    }
  })
}

// 日期时间选择器的禁用时间
const disabledDate = (time) => {
  // 禁用过去的日期
  return time.getTime() < Date.now() - 8.64e7 // 8.64e7 是一天的毫秒数
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  return timeUtils.formatLocal(dateTimeStr);
}

// 计算是否有时间冲突
const hasTimeConflict = computed(() => {
  return conflictingReservations.value.length > 0
})
</script>

<template>
  <div class="new-reservation-container">
    <div class="page-header">
      <h2>预约会议室</h2>
    </div>
    
    <el-card shadow="hover" class="form-card">
      <el-form
        ref="reservationFormRef"
        :model="reservationForm"
        :rules="reservationFormRules"
        label-width="100px"
      >
        <el-form-item label="会议室" prop="roomId">
          <el-select 
            v-model="reservationForm.roomId" 
            placeholder="请选择会议室" 
            style="width: 100%"
            @change="handleRoomChange"
          >
            <el-option 
              v-for="room in rooms" 
              :key="room.id" 
              :label="`${room.name} (容纳${room.capacity}人)`" 
              :value="room.id" 
            />
          </el-select>
        </el-form-item>
        
        <el-form-item v-if="selectedRoom" label="会议室信息">
          <div class="room-info">
            <p><strong>位置：</strong>{{ selectedRoom.location || '未设置' }}</p>
            <p><strong>设备：</strong>{{ selectedRoom.equipment || '无' }}</p>
          </div>
        </el-form-item>
        
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker
            v-model="reservationForm.startTime"
            type="datetime"
            placeholder="选择开始时间"
            style="width: 100%"
            :disabled-date="disabledDate"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '22:00'
            }"
            @change="handleTimeChange"
          />
        </el-form-item>
        
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker
            v-model="reservationForm.endTime"
            type="datetime"
            placeholder="选择结束时间"
            style="width: 100%"
            :disabled-date="disabledDate"
            :picker-options="{
              start: '08:00',
              step: '00:30',
              end: '22:00'
            }"
            @change="handleTimeChange"
          />
        </el-form-item>
        
        <el-form-item label="用途" prop="purpose">
          <el-input 
            v-model="reservationForm.purpose" 
            type="textarea" 
            :rows="3" 
            placeholder="请简述会议用途"
          />
        </el-form-item>
        
        <el-form-item label="参会人数" prop="attendees">
          <el-input-number 
            v-model="reservationForm.attendees" 
            :min="1" 
            :max="1000" 
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm" :disabled="hasTimeConflict">提交预约</el-button>
          <el-button @click="router.push('/my-reservations')">取消</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 显示时间冲突警告 -->
      <div v-if="hasTimeConflict" class="conflict-warning">
        <el-alert
          title="时间冲突提示"
          type="error"
          description="您选择的时间段已被预约，请重新选择时间"
          show-icon
          :closable="false"
        />
        
        <el-table
          :data="conflictingReservations"
          border
          style="width: 100%; margin-top: 10px;"
        >
          <el-table-column prop="room.name" label="会议室" />
          <el-table-column label="开始时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.startTime) }}
            </template>
          </el-table-column>
          <el-table-column label="结束时间">
            <template #default="scope">
              {{ formatDateTime(scope.row.endTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="purpose" label="用途" />
          <el-table-column prop="status" label="状态">
            <template #default="scope">
              <el-tag 
                :type="scope.row.status === 'APPROVED' ? 'success' : 
                       scope.row.status === 'PENDING' ? 'warning' : 'info'"
              >
                {{ scope.row.status === 'APPROVED' ? '已批准' : 
                   scope.row.status === 'PENDING' ? '待审批' : scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.new-reservation-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
}

.form-card {
  margin-bottom: 20px;
  max-width: 800px;
}

.room-info {
  background-color: #f8f8f8;
  padding: 10px;
  border-radius: 4px;
}

.room-info p {
  margin: 5px 0;
}

.conflict-warning {
  margin-top: 20px;
}
</style>